package com.flower.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flower.domain.ApiResult;
import com.flower.domain.entity.category.Category;
import com.flower.domain.entity.category.CategoryParam;
import com.flower.domain.entity.category.CategoryVo;
import com.flower.service.CategoryService;
import com.flower.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 后台商品列表控制层
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class BackageCategoryController {

    @Resource
    private CategoryService categoryService;

    /**
     * 分类列表
     * @param param 查询参数
     * @return
     */
    @PostMapping("/list")
    public ApiResult<Map<String,Object>> categoryList(@RequestBody CategoryParam param){
        //构建分页查询
        Page<Category> categoryPage = new Page<>(param.getPage(),param.getSize());
        //构建条件查询语句
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq();
        //wrapper.orderByDesc(Category::getIsFa);
        //wrapper.orderByAsc(Category::getSort);
        //向数据库查询
        Page<Category> page1 = categoryService.page(categoryPage, wrapper);
        //拷贝至vo类
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(page1.getRecords(), CategoryVo.class);

        //使用 stream 流将子分类装载值 父分类children
        /*
        List<CategoryVo> collect = categoryVos.stream()
                .filter(categoryVo -> categoryVo.getPid() != null)
                .collect(Collectors.toList());
        //循换没有剔除子分类的分类
        for (CategoryVo categoryVo : categoryVos) {
            List<CategoryVo> categoryVoList = new ArrayList<>();
            //子分类的分类
            for (CategoryVo vo : collect) {
                //如果子分类的父id等于分类的id 装载进去
                if(vo.getPid().toString().equals(categoryVo.getId().toString())){
                    categoryVoList.add(vo);
                }
            }
        }
            //新建map
            //bug 后台数据 返回
            原因：后台传过去的json数据用了阿里的fastjson转换，但是解析list中引用的数据时，
            jvm会自动将其处理为“循环引用”，因此，也就出现了问题{"r e f " : " ref":"ref":".data[0].children[0]"}，
            数据以引用的方式传给前台，前台却无法解析到那段引用的数据。
            循环引用就是：当一个对象包含另一个对象时，fastjson就会把该对象解析成引用。
            解决方案 JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect)

         */
        List<CategoryVo> collect = categoryVos.stream().filter(item -> item.getPid() != null)
                .collect(Collectors.toList());
        //拿到所有父级分类
        List<Category> categories = categoryFather();
        //将该父级分类的id name 加载至分类上
        for (Category category : categories) {
            for (CategoryVo vo : collect) {
                if(vo.getPid().toString().equals(category.getId().toString())){
                    vo.setParentClassifyId(category.getId());
                    vo.setParentClassifyName(category.getCateName());
                }
            }
        }
        Map<String,Object> map = new LinkedHashMap<>(2);
        map.put("content",categoryVos);
        map.put("total",page1.getTotal());
        //构建map 将数据返回
        return ApiResult.ok(map);
    };

    /**
     * 先查询出所有的父级分类
     * @return
     */
    public List<Category> categoryFather(){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getIsFa,1);
        wrapper.orderByAsc(Category::getSort);
        return categoryService.list(wrapper);
    }


    /**
     * 删除
     * @param id id
     * @return
     */
    @GetMapping("/delete/{id}")
    public ApiResult<Boolean> categoryDelete(@PathVariable Long id){
        categoryService.removeById(id);
        return ApiResult.ok();
    }

    /**
     * 增加或修改一个分类
     * @param category
     * @return
     */
    @PostMapping("/addEdit")
    public ApiResult<Boolean> categoryAdd(@RequestBody Category category) {
        if(!Objects.isNull(category.getId())){
            log.warn("修改");
            LambdaUpdateWrapper<Category> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Category::getId,category.getId());
            wrapper.set(Category::getCateName,category.getCateName());
            wrapper.set(Category::getPid,category.getPid());
            wrapper.set(Category::getIsFa,category.getIsFa());
            categoryService.update(wrapper);
            return ApiResult.ok();
        }
        categoryService.save(category);
        return ApiResult.ok();
    }

    @GetMapping("/getFcategory")
    public ApiResult<List<Category>> FaCategoryList() {
        return ApiResult.ok(categoryFather());
    }

    /**
     * 获取分类列表节点
     *
     * @param clickCategoryId
     * @return
     */
    @GetMapping("/getCcategory")
    public ApiResult<List<Category>> ChCategoryList(@RequestParam Long clickCategoryId) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (clickCategoryId == 0L) {
            wrapper.eq(Category::getIsFa, 1);
        } else {
            wrapper.eq(Category::getPid, clickCategoryId);
        }
        List<Category> list = categoryService.list(wrapper);
        return ApiResult.ok(list);
    }


}
